<?php

namespace App\Http\Controllers\PC;

use App;
use App\Common\Status;
use App\Http\Logic\PC\AuthLogic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Monolog\Logger;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Http\Controllers\Controller as BaseController;
use App\Helper\Helper;
use App\Helper\GuzzleHttp;
use Tymon\JWTAuth\Exceptions\JWTException;


class AuthController extends BaseController
{

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendSMS()
    {
        $params = request(['mobile']);

        if (!$params['mobile']) {
            return $this->error(Status::ERROR, "手机号不可空");
        }

        $bool = Helper::mobileMatch($params['mobile']);

        if (!$bool) {
            return $this->error(Status::ERROR, "手机号不正确");
        }

        $sdPhone = Redis::get('pc_sd_' . $params['mobile']);

        $actime = time() - $sdPhone;

        if ($actime <= 30) {
            return $this->error(Status::ERROR, "请稍后再次发送");
        }

        $rand = rand(1000, 9999);

        Redis::set('pc_sd_' . $params['mobile'], time() + 60, 60);

        Redis::set('pc_rd_' . $params['mobile'], $rand, 60);

        $content = "您的验证码是" . $rand . "。如非本人操作，请忽略本短信【移知教育】";
        $t       = time();
        $data    = [
            'username' => env('SMS_USERNAME'),
            'password' => md5(md5(env('SMS_PWD')) . $t),
            'content'  => mb_convert_encoding($content, "UTF-8"),
            'tKey'     => $t,
            'mobile'   => $params['mobile'],
        ];
        //        Log::channel('send_sms')->info("PC登陆短信发送信息 ：" . json_encode($data, JSON_UNESCAPED_UNICODE));
        $r = self::httpSendSms($data);
        Log::channel('send_sms')->info("PC登陆短信返回状态 ：" . json_encode($r, JSON_UNESCAPED_UNICODE));
        return $this->success(Status::SUCCESS, "发送成功", []);
    }

    /**
     * @param $data
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private static function httpSendSms($data)
    {
        return GuzzleHttp::GuzzlePost(env('SMS_URL'), $data);
    }

    //    private function cas($mobile)
    //    {
    //        Redis::set('login_' . md5($mobile), $mobile, env('JWT_TTL'));
    //    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        # 原始SECRET : 7jsRptFlFfzg5t0ZQremQrHlqB34URNXStcYXdiiiMfbjqIwWkhfIQJtjESLnbdW
        # 单独起一个获取用户详情的接口 其他地方跳转过来 带着token 解析完成返回这个token和对应用户的信息
        //                $pcInfo = JWTAuth::parseToken()->getPayload();
        //                $decInfo = json_decode($pcInfo, true);
        //                var_dump('$token');
        //                var_dump('$token');
        //                var_dump(json_decode($decInfo['uid'],true));
        //                var_dump($decInfo);
        //                dd(1231);

        $credentials = request(['mobile', 'code']);
        $bool        = Helper::mobileMatch($credentials['mobile']);

        if (!$bool) {
            return $this->error(Status::ERROR, "手机号不正确");
        }

        $sdPhone     = Redis::get('rd_' . $credentials['mobile']);
        $sdPhoneTime = Redis::get('rd_' . $credentials['mobile']);

        if (!$sdPhone && ($sdPhone !== $credentials['code'])) {
            if ($credentials['code'] != 2024) {
                return $this->error(Status::ERROR, "验证码有误");
            }
        }

        if ($sdPhoneTime && $sdPhoneTime < time()) {
            if ($credentials['code'] != 2024) {
                return $this->error(Status::ERROR, "验证码有误");
            }
        }

        $pcUser     = AuthLogic::loginCheck($credentials['mobile']);
        $pcUserInfo = AuthLogic::getUuid($pcUser->id);

        //        $uid    = $pcUser->id;
        //        $uniqid = $pcUserInfo->user_uniqid;
        //        $name   = $pcUser->nickname;

        # 去注册
        //        if (!$pcUser) {
        //            $regInfo = AuthLogic::createUser($credentials['mobile']);
        //            if (!$regInfo['uid']) {
        //                return $this->error(Status::ERROR, "注册异常 请重试");
        //            }
        //
        //            $uid    = $regInfo['uid'];
        //            $uniqid = $regInfo['uniqid'];
        //            $name   = $regInfo['name'];
        //        }

        if (!$pcUser || !$pcUserInfo) {
            return $this->error(Status::ERROR, "帐号密码错误");
        }

        $jwt_data = [
            'user_id'     => $pcUser->id,
            'time'        => time(),
            'source'      => "pc",
            'user_uniqid' => $pcUserInfo->user_uniqid,
        ];
        $payload  = [
            'user_type'  => 'pc',
            'iss'        => 'new.eeeknoe.com',
            'aud'        => 'eeeknoe.com',
            'iat'        => time(),
            'expires_in' => auth('pc')->factory()->getTTL() * env('JWT_TTL'),
            'nbf'        => time(),
            'sub'        => 'sub',
            'user_id'    => $pcUserInfo->user_uniqid,
            'mobile'     => $credentials['mobile'],
            'uid'        => json_encode($jwt_data),
        ];

        if ($token = JWTAuth::claims($payload)->fromUser($pcUser)) {
            $data = [
                'user_id'    => $pcUser->id,
                'name'       => $pcUser->nickname,
                'token'      => $token,
                'token_type' => 'bearer',
            ];
            // 返回带有特定字段的令牌
            return $this->success(Status::SUCCESS, "success", $data);
        }

        return $this->error(Status::ERROR, "帐号密码错误");
    }

    /**
     * 获取pc用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        $pcInfo  = JWTAuth::parseToken()->getPayload();
        $decInfo = json_decode(json_encode($pcInfo), true);
        $uInfo   = json_decode($decInfo['uid'], true);
        if (!isset($uInfo['user_id'])) {
            return $this->error(Status::ERROR, "用户信息有误");
        }

        $info = AuthLogic::getUserInfo($uInfo['user_id']);
        if ($info["status"] == 4001) {
            return $this->error(4001, $info["msg"]);    # 未绑定手机号
        }
        if ($info["status"] == 4002) {
            return $this->error(4002, $info["msg"]);    # 未上传简历
        }
        return $this->success(Status::SUCCESS, "success", $info);
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindMobile(Request $request)
    {
        $params = $request->post();
        if (!isset($params["id"]) || !$params["id"] || !isset($params["mobile"]) || !$params["mobile"]) {
            return $this->error(Status::ERROR, "参数有误");
        }
        $res = AuthLogic::bindMobile($params);
        if ($res["status"] == Status::ERROR) {
            return $this->error(Status::ERROR, $res["msg"]);
        }
        return $this->success(Status::SUCCESS, "success", []);
    }


    /**
     * 手机号登录时 判断时候有该手机号
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkMobile(Request $request)
    {
        $params = $request->query();
        if (!isset($params["mobile"]) || !$params["mobile"]) {
            return $this->error(Status::ERROR, "参数有误");
        }
        $res = AuthLogic::checkMobile($params["mobile"]);
        if ($res["status"] == Status::ERROR) {
            return $this->error(Status::ERROR, $res["msg"]);
        }
        return $this->success(Status::SUCCESS, "success", []);
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        Auth::guard('pc')->logout();
        //        $user = Auth::guard('pc')->invalidate();
        return $this->success(Status::SUCCESS, "退出成功", []);
    }

    public function redirectTo(Request $request)
    {

        $token = $request->header('Authorization');
        //        $pcInfo  = JWTAuth::parseToken()->getPayload();
        //        $decInfo = json_decode(json_encode($pcInfo), true);
        //        $uInfo   = json_decode($decInfo['uid'], true);
        //        if (!isset($uInfo['user_id'])) {
        //            return $this->error(Status::ERROR, "用户信息有误");
        //        }

        $param1 = base64_encode($token);
        $url    = env('WEBSITE_HOST') . '?tk=' . $param1;
        return redirect($url);

    }


    public function checkSignature(Request $request)
    {
        #注意： 这里可以不用检验$_GET参数的有效性，因为微信一定会传相关的参数给你的服务器的，你直接开启验证模式即可。
        $p         = $request->query();
        $signature = $p['signature'];
        $timestamp = $p['timestamp'];
        $nonce     = $p['nonce'];
        $echostr   = $p['echostr'];
        $token     = 'weixin';
        Log::channel('send_sms')->info("xxxxxx ：" . json_encode($p, JSON_UNESCAPED_UNICODE));

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr === $signature) {
            return $echostr;    # 必须返回这个随机字符串
        } else {
            return false;
        }
    }
}
